package lumis.portal.serialization.persistency.fs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import lumis.util.PortalUtil;

/**
 * {@link FSDirectory} variant that stores all files in the root directory, mapping each file path to a GUID.
 *
 * @version $Revision: 6376 $ $Date: 2007-04-10 17:55:53 -0300 (Tue, 10 Apr 2007) $
 * @since 4.0.10
 */
public class FSShallowDirectory extends FSDirectory
{
	private Map<String, String> pathMappings = new HashMap<String, String>();

	public FSShallowDirectory(String rootPath)
	{
		super(rootPath);
	}

	public FSShallowDirectory(File root)
	{
		super(root);
	}

	@Override
	public synchronized void close() throws IOException
	{
		super.close();
		pathMappings.clear();
	}

	@Override
	public synchronized boolean exists(String filePath) throws IOException
	{
		return pathMappings.containsKey(filePath);
	}

	@Override
	public String getDescription()
	{
		return this.getClass().getName() + " rootPath=" + rootFile.getAbsolutePath();
	}

	@Override
	public synchronized InputStream getInputStream(String filePath) throws FileNotFoundException, IOException
	{
		if (!exists(filePath))
			throw new FileNotFoundException("File '" + filePath + "' was not found.");
		return super.getInputStream(mapPath(filePath));
	}

	@Override
	public synchronized OutputStream getOutputStream(String filePath) throws IOException
	{
		return super.getOutputStream(mapPath(filePath));
	}

	private synchronized String mapPath(String path)
	{
		String mappedPath = pathMappings.get(path);
		if (mappedPath == null)
		{
			mappedPath = PortalUtil.generateNewGuid();
			pathMappings.put(path, mappedPath);
		}
		return mappedPath;
	}
}
